# -*- coding=utf-8 -*-

import requests
import lxml.etree as le
import re
import os
import time
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0'
}
proxies = {
    'http:' : ''
}
major_url = 'http://www.k1k.cc'

def search(kw):
    '''
    本函数用来搜索关键词，并由用户选择要下载的视频
    :param kw: 要搜索的关键词
    :return: 选择后的视频的简介页的链接
    '''
    url = 'http://www.k1k.cc/movie/search/'
    data = {"skey" : kw, "submit" : "搜索电影"}
    req = requests.post(url = url, headers=headers, data=data).text
    # while True:
    #     try:
    #         req = requests.get(url = url, headers = headers).text
    #     except:
    #         print('正在重试...')
    #         time.sleep(1.3)
    #         continue
    result = []
    print('{:2s}: {:^30s} {:^30s}'.format('序号', '搜索结果名称', '类型/最新集数'))
    for i, uc in enumerate(le.HTML(req).xpath('//ul[@class="img-list clearfix"]/li')[1:]):
        name = uc.xpath('./h5/a/@title')[0]
        url = major_url + uc.xpath('./h5/a/@href')[0]
        mark = uc.xpath('./a/em/text()')[0] if len(uc.xpath('./a/em/text()')) != 0 else ''
        result.append(
            {
                'name' : name,
                'url' : url
            }
        )
        print('{:>2d}: {:^30s} {:^30s}'.format(i + 1, name, mark))
        # print('%d: %s\t%s' % (i + 1, name, type))
    choose = eval(input('请选择要下载的视频序号：')) - 1
    print(result[choose])
    return result[choose]

def get_index_url(url_dict):
    '''
    本函数用来获得每个视频的播放页
    :param url: 视频的简介页的链接
    :return: 每个视频播放页的的链接
    '''

    name = url_dict['name']
    i_url = url_dict['url']
    result = {name : []}
    req = requests.get(i_url, headers = headers).text
    video_list = le.HTML(req).xpath('//ul/a')
    for video in video_list[1:]:
        url = major_url + video.xpath('./@href')[0]
        v_name = video.xpath('./text()')[0]
        result[name].append(
            {
                'name' : name + v_name,
                'url' : url
            }
        )
    return result


def download_video(r_dict, f_path = '.'):
    '''
    本函数用来下载视频
    :param r_list: 包含视频链接
    :return: None
    '''
    for name in r_dict.keys():

        r_list = r_dict.get(name)
        path = os.path.join(f_path, name)
        if not os.path.exists(path):
            os.mkdir(path)
        print('共有 %d 个视频需要下载' % len(r_list))
        m_url = 'https://hong.tianzhen-zuida.com'
        for r in r_list:
            if os.path.exists(os.path.join(path, r.get('name')) + '.mp4'):
                continue

            print('%s 正在下载...' % r.get('name'))
            url = r.get('url')
            req = requests.get(url, headers = headers).text
            v_path = le.HTML(req).xpath('//iframe/@src')[0]
            # print(v_path)
            video_text = requests.get(v_path, headers=headers).text
            # print(video_text)
            video_list_url = m_url + re.findall('var main = "(.*?/)index.m3u8\?sign=.*";', video_text)[0] + '1000k/hls/index.m3u8'
            # print(video_list_url)
            major = video_list_url.replace('index.m3u8', '')
            video_list = requests.get(video_list_url, headers=headers).text.split()[5::2]
            length = len(video_list)
            start_time = time.perf_counter()
            for i, file in enumerate(video_list):
                file_url = major + file
                while True:
                    try:
                        file_req = requests.get(file_url, headers = headers)
                        break
                    except:
                        time.sleep(1.3)
                        continue
                with open(os.path.join(path, r.get('name')) + '.mp4', 'ab') as f:
                    f.write(file_req.content)
                x = (i / length) * 100
                count = int(i / length * 20)
                y = '■' * count
                z = '□' * (20 - count)
                print("\r{:^3.0f}%[{}{}] {:.3f}s".format(x, y, z, time.perf_counter() - start_time), end = "")
                time.sleep(1)
            f_time = time.perf_counter() - start_time
            print("\r{:^3.0f}%[{}] {:.3f}s".format(100.00, '■' * 20, f_time))
            with open('./time.log', 'a') as f:
                f.write(r.get('name') + '下载完毕，所用时间：' + '\t' + str(f_time) + 's\n')
            print('%s 已经下载完毕...\n' % r.get('name'))

kw = input('请输入要搜索的关键词:')
r_dict = get_index_url(search(kw))
file_path = input('请输入保存地址:').replace('\\', '/')
download_video(r_dict, file_path)